package com.example.aliyun.plus;

/**
 * 线程强制执行
 */
public class ThreadJoin {
    public static void main(String[] args) {
        Thread mainThread = Thread.currentThread();
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                if (i > 5) {
                    try {
                        mainThread.join(); // 主线程加入独占资源
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行了 i = " + i);
            }
        },"子线程");
        thread.start();
        // 主线程加入
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(mainThread.getName() + " 线程执行-------> i = " + i);
        }
    }
}
